import { Reducer } from "react";
import { Editor } from "../types";

type EditorActionType = "select" | "UPDATE_GS" | "UPDATE_CS";

type EditorAction = {
  type: EditorActionType;
  payload?: any;
};

const editorReducer: Reducer<Editor, EditorAction> = (preState, action) => {
  switch (action.type) {
    case "select":
      return { ...preState, curSelectedWidgetId: action.payload.id };
    case "UPDATE_GS":
      return { ...preState, golbalSettings: action.payload };
    case "UPDATE_CS":
      let id = action.payload.id;
      let newConfig = action.payload.config;
      const newList = preState.widgetList.map((w) => {
        if (w.id === id) {
          w.config = newConfig;
        }
        return w;
      });
      return { ...preState, widgetList: newList };
    default:
      return preState;
  }
};

export type { EditorAction };

export { editorReducer };
